﻿using System.Threading.Tasks;
using AutoMapper;
using GMS.IServices;
using GMS.IServices.Jwt;
using GMS.Models.Jwt;
using GMS.Models.Other;
using GMS.Models.ResponseDto;
using Microsoft.AspNetCore.Mvc;

namespace GMS.API.Controllers
{
    [ApiController]
    [Route("Login")]
    public class LoginController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly IUserInfoService _userInfoService;
        private readonly IJwtService _jwtService;


        public LoginController(IMapper mapper, IUserInfoService userInfoService, IJwtService jwtService)
        {
            _mapper = mapper;
            _userInfoService = userInfoService;
            _jwtService = jwtService;
        }

        [HttpPost("user")]
        public async Task<IActionResult> Login(Login login)
        {
            var entity = await _userInfoService.LoginAsync(login.UserName, login.PassWord);
            if (entity == null)
            {
                return StatusCode(400, new { code = 400, message = "账号或密码错误,请重新登陆" });
            }

            Payload payload = new Payload()
            {
                Id = entity.Id,
                Name = entity.UserName
            };
            var token = await _jwtService.GenerateTokenAsync(payload);

            return StatusCode(200, new { code = 200, message = "登陆成功", data = new { userInfo = payload, token } });
        }
    }
}